/**
 * admui-basic v2.1.0 (http://www.admui.com/)
 * Copyright 2015-2019 Admui Team
 * Licensed under the Admui License 1.1 (http://www.admui.com/about/license)
 */
(function(document, window, $) {
  'use strict';

  /* global toastr */

  var $exampleFullCropper = $('#exampleFullCropper img');
  var $inputDataX = $('#inputDataX');
  var $inputDataY = $('#inputDataY');
  var $inputDataHeight = $('#inputDataHeight');
  var $inputDataWidth = $('#inputDataWidth');

  // 简单示例
  $('#simpleCropper img').cropper({
    preview: '#simpleCropperPreview >.img-preview',
    responsive: true
  });

  // 复杂示例
  $exampleFullCropper.cropper({
    aspectRatio: 16 / 9,
    preview: '#exampleFullCropperPreview > .img-preview',
    responsive: true,
    crop: function() {
      var data = $(this).data('cropper');

      if (typeof data !== 'undefined') {
        data = data.getCropBoxData();
        $inputDataX.val(Math.round(data.left));
        $inputDataY.val(Math.round(data.top));
        $inputDataHeight.val(Math.round(data.height));
        $inputDataWidth.val(Math.round(data.width));
      }
    }
  });

  // 功能按钮
  $('[data-cropper-method]').on('click', function() {
    var data = $(this).data();
    var method = $(this).data('cropper-method');
    var result;

    if (method) {
      result = $exampleFullCropper.cropper(method, data.option);
    }

    if (method === 'getCroppedCanvas') {
      $('#getDataURLModal').modal();
      $('#getImageData').html(result);
    }
  });

  // 处理上传
  $('#inputImage').change(function() {
    var $item = $(this);
    var fileReader = new FileReader();
    var files = this.files;
    var file;

    if (!files.length) {
      return;
    }

    file = files[0];

    if (/^image\/\w+$/.test(file.type)) {
      fileReader.readAsDataURL(file);
      fileReader.onload = function() {
        $exampleFullCropper.cropper('reset', true).cropper('replace', this.result);
        $item.val('');
      };
    } else {
      toastr.warnings('请选择图片文件');
    }
  });

  // 设置数据
  $('#setCropperData').click(function() {
    $exampleFullCropper.cropper('setCropBoxData', {
      left: parseInt($inputDataX.val(), 10),
      top: parseInt($inputDataY.val(), 10),
      width: parseInt($inputDataWidth.val(), 10),
      height: parseInt($inputDataHeight.val(), 10)
    });
  });
})(document, window, jQuery);
